import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "@/contexts/authContext.js";
import { motion } from "framer-motion";
import { 
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, LineChart, Line
} from "recharts";
import { toast } from "sonner";

// 模拟数据
const salesData = [
  { name: '1月', value: 400 },
  { name: '2月', value: 300 },
  { name: '3月', value: 500 },
  { name: '4月', value: 280 },
  { name: '5月', value: 590 },
  { name: '6月', value: 430 },
];

const userActivityData = [
  { name: '周一', 新增用户: 40, 活跃用户: 24 },
  { name: '周二', 新增用户: 30, 活跃用户: 13 },
  { name: '周三', 新增用户: 50, 活跃用户: 29 },
  { name: '周四', 新增用户: 38, 活跃用户: 30 },
  { name: '周五', 新增用户: 48, 活跃用户: 39 },
  { name: '周六', 新增用户: 38, 活跃用户: 48 },
  { name: '周日', 新增用户: 43, 活跃用户: 38 },
];

const productCategoriesData = [
  { name: '电子产品', value: 400 },
  { name: '服装', value: 300 },
  { name: '食品', value: 300 },
  { name: '图书', value: 200 },
  { name: '其他', value: 100 },
];

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8'];

export default function Dashboard() {
  const { user, logout } = useAuth();
  const [stats, setStats] = useState({
    totalUsers: 0,
    totalProducts: 0,
    totalSales: 0,
    activeUsers: 0
  });

  // 模拟数据加载
  useEffect(() => {
    // 模拟异步数据获取
    const timer = setTimeout(() => {
      setStats({
        totalUsers: 1280,
        totalProducts: 256,
        totalSales: 125000,
        activeUsers: 456
      });
    }, 800);

    return () => clearTimeout(timer);
  }, []);

  const handleLogout = () => {
    logout();
    toast.success("已成功退出登录");
  };

  // 数字格式化
  const formatNumber = (num) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex flex-col">
      {/* 顶部导航 */}
      <header className="bg-white dark:bg-gray-800 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
          <div className="flex items-center space-x-2">
            <i className="fa-solid fa-chart-line text-indigo-600 dark:text-indigo-400 text-xl"></i>
            <h1 className="text-xl font-bold text-gray-900 dark:text-white">管理控制台</h1>
          </div>
          
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2">
              <div className="w-8 h-8 rounded-full bg-indigo-100 dark:bg-indigo-900 flex items-center justify-center text-indigo-600 dark:text-indigo-300">
                <i className="fa-solid fa-user"></i>
              </div>
              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                {user?.username}
              </span>
            </div>
            
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={handleLogout}
              className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
            >
              <i className="fa-solid fa-right-from-bracket"></i>
            </motion.button>
          </div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="flex-grow max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 用户欢迎信息 */}
        <div className="mb-8">
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
            欢迎回来，{user?.username}
          </h2>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            今天是 {new Date().toLocaleDateString()}，这是您的系统概览
          </p>
        </div>

        {/* 快速统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          {[
            { 
              title: '总用户数', 
              value: stats.totalUsers, 
              icon: 'fa-solid fa-users', 
              color: 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400',
              link: '/users'
            },
            { 
              title: '总产品数', 
              value: stats.totalProducts, 
              icon: 'fa-solid fa-box', 
              color: 'bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-400',
              link: '/products'
            },
            { 
              title: '总销售额', 
              value: stats.totalSales, 
              icon: 'fa-solid fa-chart-line', 
              color: 'bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400',
              format: (v) => `¥${formatNumber(v)}`
            },
            { 
              title: '活跃用户', 
              value: stats.activeUsers, 
              icon: 'fa-solid fa-user-check', 
              color: 'bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400'
            }
          ].map((stat, index) => (
            <motion.div
              key={index}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1 }}
              className="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden"
            >
              <Link 
                to={stat.link || '#'} 
                className={`p-6 ${!stat.link && 'cursor-default'}`}
                onClick={(e) => !stat.link && e.preventDefault()}
              >
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-gray-500 dark:text-gray-400">{stat.title}</p>
                    <h3 className="mt-1 text-2xl font-bold text-gray-900 dark:text-white">
                      {stat.format ? stat.format(stat.value) : formatNumber(stat.value)}
                    </h3>
                  </div>
                  <div className={`p-3 rounded-lg ${stat.color}`}>
                    <i className={stat.icon} size={24}></i>
                  </div>
                </div>
              </Link>
            </motion.div>
          ))}
        </div>

        {/* 图表区域 */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
          {/* 销售趋势图 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 lg:col-span-2"
          >
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">销售趋势</h3>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={salesData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis dataKey="name" tick={{ fill: '#9ca3af' }} />
                  <YAxis tick={{ fill: '#9ca3af' }} />
                  <Tooltip />
                  <Bar dataKey="value" fill="#6366f1" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </motion.div>

          {/* 产品分类饼图 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6"
          >
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">产品分类</h3>
            <div className="h-80 flex items-center justify-center">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={productCategoriesData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {productCategoriesData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </motion.div>
        </div>

        {/* 用户活动图表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6"
        >
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">用户活动</h3>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={userActivityData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis dataKey="name" tick={{ fill: '#9ca3af' }} />
                <YAxis tick={{ fill: '#9ca3af' }} />
                <Tooltip />
                <Line type="monotone" dataKey="新增用户" stroke="#6366f1" strokeWidth={2} dot={{ r: 4 }} />
                <Line type="monotone" dataKey="活跃用户" stroke="#10b981" strokeWidth={2} dot={{ r: 4 }} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </motion.div>

        {/* 快速操作 */}
        <div className="mt-8">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">快速操作</h3>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
            {[
              { title: '添加用户', icon: 'fa-user-plus', color: 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400', route: '/users' },
              { title: '添加产品', icon: 'fa-box-plus', color: 'bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-400', route: '/products' },
               { title: '查看订单', icon: 'fa-file-invoice', color: 'bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400' },
               { title: '系统设置', icon: 'fa-gear', color: 'bg-gray-50 dark:bg-gray-700/50 text-gray-600 dark:text-gray-400', route: '/settings' }
            ].map((action, index) => (
              <motion.div
                key={index}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <Link 
                  to={action.route || '#'}
                  className={`flex flex-col items-center justify-center p-4 rounded-xl ${action.color}`}
                  onClick={(e) => !action.route && e.preventDefault()}
                >
                  <i className={`fa-solid ${action.icon} text-xl mb-2`}></i>
                  <span className="text-sm font-medium">{action.title}</span>
                </Link>
              </motion.div>
            ))}
          </div>
        </div>
      </main>

      {/* 页脚 */}
      <footer className="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 py-4">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex justify-between items-center">
          <p className="text-sm text-gray-500 dark:text-gray-400">
            © 2025 React学习管理系统 | 前端开发最佳实践
          </p>
          <div className="flex items-center space-x-4">
            <span className="text-sm text-gray-500 dark:text-gray-400">
              角色: {user?.role}
            </span>
          </div>
        </div>
      </footer>
    </div>
  );
}